package com.sskj.motherboard.service.impl;

import com.sskj.motherboard.server.ClientManager;
import com.sskj.motherboard.service.IMotherboardService;
import com.sskj.motherboard.vo.FrameMessage;
import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class MotherboardService implements IMotherboardService {

    @Override
    public boolean pushCameraStream(String deviceId, Integer channelNumber, Integer videoQualityType) {
        Channel channel = ClientManager.getChannel(deviceId);
        log.info("deviceId:{}|channel={}", deviceId, channel);
        if (channel != null && channel.isActive()) {
            FrameMessage frameMessage = new FrameMessage();
            frameMessage.setCommandCode((byte) 0x01);
            frameMessage.setCommandType((byte) 0x02);

            // 组装数据帧正文
            byte[] sessionIdBytes = deviceId.getBytes(StandardCharsets.UTF_8);
            byte channelNumberByte = channelNumber.byteValue();
            byte videoQualityTypeByte = videoQualityType.byteValue();
            byte[] data = new byte[1+1+sessionIdBytes.length];
            data[0] = channelNumberByte;
            data[1] = videoQualityTypeByte;
            System.arraycopy(sessionIdBytes, 0, data, 2, sessionIdBytes.length);
            frameMessage.setData(data);

            channel.writeAndFlush(frameMessage);

            return true;
        }
        return false;
    }

    @Override
    public void stopCameraStream(String deviceId, Integer channelNumber) {
        Channel channel = ClientManager.getChannel(deviceId);
        if (channel != null && channel.isActive()) {
            FrameMessage frameMessage = new FrameMessage();
            frameMessage.setCommandCode((byte) 0x02);
            frameMessage.setCommandType((byte) 0x02);

            // 组装数据帧正文
            byte channelNumberByte = channelNumber.byteValue();
            byte[] sessionIdBytes = deviceId.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[1 + sessionIdBytes.length];
            data[0] = channelNumberByte;
            System.arraycopy(sessionIdBytes, 0, data, 1, sessionIdBytes.length);
            frameMessage.setData(data);

            channel.writeAndFlush(frameMessage);
        }
    }
}
